# 符号回归
# 符号回归是一种机器学习方法，它通过构建一个符号表达式来拟合数据，而不是使用传统的数值模型。
# 符号回归的优点是它可以自动选择特征，并且可以处理非线性关系。
# 符号回归的缺点是它需要大量的计算资源，并且可能需要很长时间才能找到最佳模型。


import pandas as pd
from gplearn.genetic import SymbolicRegressor
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error, max_error
from sklearn.model_selection import train_test_split
import numpy as np

# 1. 读取数据
data = pd.read_csv('data.csv', sep='\t')

# 2. 计算dt特征
data['dt'] = data['t_hf_wetbulb'] - data['outlet_water_temp']

# 3. 特征与标签
target = 'heat_load'
features = ['freq_all', 'flow', 'dt', 'freq_all_flow']
X = data[features].values
y = data[target].values
print(X)
print(y)
# 4. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 5. 构建并训练符号回归模型
gp = SymbolicRegressor(
    population_size=2000,
    generations=30,
    stopping_criteria=0.01,
    p_crossover=0.7,
    p_subtree_mutation=0.1,
    p_hoist_mutation=0.05,
    p_point_mutation=0.1,
    max_samples=0.9,
    verbose=1,
    parsimony_coefficient=0.01,
    random_state=42
)
gp.fit(X_train, y_train)

# 6. 输出最佳公式
print('\n最佳符号回归公式:')
print(gp._program)

# 7. 评价指标
y_pred = gp.predict(X_test)
print('\n【gplearn符号回归测试集结果】')
print('R2:', r2_score(y_test, y_pred))
print('MSE:', mean_squared_error(y_test, y_pred))
print('MAE:', mean_absolute_error(y_test, y_pred))
print('Max Error:', max_error(y_test, y_pred)) 